import React from 'react'
import { Table,Icon,Modal,Popconfirm,Form,Input,Row,Col,DatePicker,Button,Message,Select,Upload} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
import api from '../../../api/platDeviceRegister';

const { RangePicker } = DatePicker;
import moment from 'moment';

import PanelBox from '../../../components/PanelBox';
import {jsonToTree} from '../../../utils/tools'
import { reqToken } from "../../../utils/reqTools";
import { INTERFACE_CORE_URL } from '../../../api/config';

import '../../../style/antd-theme.less';
const pageRouter = '/plat/deviceRegister';

export default class TablePage extends React.Component { 
  state = {
    data: [],
    pagination: {
      pageSize:20,
      pageNum:1,
    },
    loading: false, 
    officeId:'',
    importUrl: '',
    exportUrl: '',
    exportCodeUrl:''
  };
  handleTableChange = (pagination, filters, sorter) => {
    pagination.pageNum=pagination.current;
    this.setState({pagination});
   
    this.fetch({...pagination});
  }
  fetch = (params) => {
    this.setState({ loading: true });
    api.get('/hardRegister/getAll', { params}).then((data) => {
      const _data = data.data.list;
      const pagination = { ...this.state.pagination };
      pagination.total = data.data.total;
      this.setState({
        loading: false,
        data: _data,
        pagination,
      });
    });
  }

  componentDidMount = () =>{
    let user =this.props.profile.user;
    this.setState({
      userSession:user,
      officeId:user.officeId
      });
    this.fetch({ ...this.state.pagination });

  }
  delete = (id,event) => {
    api.delete('/hardRegister/delete', {id:id}).then((data) => {
      const result= data.data;
     if(result.code == 0){
      Message.success('删除成功！');
      this.fetch({ ...this.state.pagination });
     }else{
      Message.error(result.message);
     }
    });
  }
  componentWillMount() {
    this._isMounted = true;
    reqToken().then(res => {
      this._isMounted && this.setState({
        importUrl: INTERFACE_CORE_URL +'/api/hardRegister/importExcel?token='+ res,
        exportUrl: INTERFACE_CORE_URL +'/api/hardRegister/exportExcel?token='+ res,
        exportCodeUrl: INTERFACE_CORE_URL +'/api/hardRegister/exportUrlExcel?token='+ res,
      })
    });
  }
  componentWillUnmount() {
    this._isMounted = false;
  }

  import = ({ fileList }) => {
    if(fileList.length > 0 && typeof(fileList[0].response) != 'undefined'){
      let codes=fileList[0].response.code;
      if(codes == 0){
        this.fetch({ ...this.state.pagination });
        Message.success(`操作成功`);
      }else if(codes == 104){
        Message.error(`长时间未操作，请重新尝试`);
        this.props.history.replace(pageRouter);
      }
    }
   
  }
  exportCodeAdree=()=>{
    window.location=this.state.exportCodeUrl;
  }
  export=()=>{
    window.location=this.state.exportUrl;
  }



  render() {
    let columns = [{
      title: '设备编号',
      dataIndex: 'deviceHardId',
      width: '20%'
    },{
      title: '设备标签',
      dataIndex: 'deviceHardSign',
      width: '25%'
    },{
      title: '设备密码',
      dataIndex: 'devicePassword',
      width: '20%',
    },{
      title:'创建时间',
      dataIndex: 'create_date',
      width: '20%',
    }, {
      title: '操作',
      render: (text, record) => (
        <span>
          <Popconfirm title="您是否要删除该记录?" onConfirm={this.delete.bind(this,record.id)} okText="是" cancelText="否">
            <a href="javascript:void(0)">删除</a>
          </Popconfirm>
        </span>
      ),
    }];
    return (
      <div>
        <SearchCostForm searchCostState={this.state} goSearch={this.handleTableChange}  import={this.import} exportCodeAdree={this.exportCodeAdree} export=
        {this.export}/>
        <PanelBox>
          <Table columns={columns}  dataSource={this.state.data}  pagination={this.state.pagination}
            loading={this.state.loading}  onChange={this.handleTableChange}  rowKey='id'
            expandedRowRender={record => <p style={{ margin: 0 }}>二维码地址 :  {record.twoDimensionUrl} </p>}
          />
        </PanelBox>
      </div>
    );
  }
}

    class SearchsForm extends React.Component {
   
      // 开始搜索
      goSearch = (e) => {
        let params=this.props.form.getFieldsValue();
        
        let _this=this.props;
        params.pageSize=_this.searchCostState.pagination.pageSize;
        params.pageNum =1;
        params.current =1;
        if(params.date.length > 0){
          params.startCreateDate=moment(params.date[0]).format("YYYY-MM-DD");
          params.endCreateDate=moment(params.date[1]).format("YYYY-MM-DD");
        }
        delete params.date;
        _this.goSearch(params);
     
      }

      srearchStyle = {
        labelCol: { span: 8},
        wrapperCol: { span: 14 },
      };
     
      render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = this.srearchStyle;
        return <Form onSubmit={this.goSearch} layout="inline" style={{marginBottom:'10px'}}>
          
          <FormItem {...formItemLayout} label="设备编号" style={{marginBottom:'10px'}}>
            {getFieldDecorator('hardId' )(
              <Input type="text" placeholder="请输入设备编号"/>
            )}
          </FormItem>
          
          <FormItem {...formItemLayout} label="设备标签">
            {getFieldDecorator('hardSign' )(
              <Input type="text" placeholder="请输入设备标签"/>
            )}
          </FormItem>
          
          <FormItem {...formItemLayout} label="创建时间" style={{marginLeft:'-50px'}}>
            {getFieldDecorator('date' ,{ initialValue:[] } )(
              <RangePicker format="YYYY/MM/DD" />
            )}
          </FormItem>
          
          <FormItem>
            <Button type="primary" icon="search" htmlType="submit">搜索</Button>
          </FormItem> 
          <FormItem>
            <Button type="primary" onClick={this.props.exportCodeAdree}>导出二维码地址</Button>
          </FormItem>
          <FormItem>
            <Button type="primary" onClick={this.props.export}>下载EXCEL模板</Button>
          </FormItem>
          <FormItem>
            <Upload 
              action={this.props.searchCostState.importUrl}
              onChange={this.props.import}
              showUploadList={false}
            >
              <Button type="primary" >导入EXCEL</Button>
            </Upload>
          </FormItem>
        </Form>
      }
    }
    const SearchCostForm = Form.create({})(SearchsForm);